package com.zhaolang.qogir.ui;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.RequiresApi;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.Toast;

import com.mob.MobSDK;
import com.zhaolang.qogir.BuildConfig;
import com.zhaolang.qogir.R;
import com.zhaolang.qogir.cache.SharePreCacheHelper;
import com.zhaolang.qogir.domain.BaseCall;
import com.zhaolang.qogir.domain.Login;
import com.zhaolang.qogir.domain.Login.LoginResp;
import com.zhaolang.qogir.domain.ReqFactory;
import com.zhaolang.qogir.util.MD5;
import com.zhaolang.qogir.util.Slog;

import java.util.ArrayList;
import java.util.List;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;

public class WelcomeLogin extends BaseActivity implements OnClickListener {

    private Context mContext;
    private ViewPager mPager;
    private RadioButton mPagerF0;
    private RadioButton mPagerF1;
    private RadioButton mPagerF2;

    private View mPagerOne;
    private View mPagerTwo;
    private View mPagerThree;
    private List<View> mViewList;
    private WelcomeAdapter mAdapter;

    private EditText mUserNameEdit;
    private EditText mSmscodeEdit;
    private Button mLoginBtn, btn_get_smsCode;

    private Login mLogin;

    private int statusCode;
    private String sStatus;
    private String mMsg;
    private String mUserName;
    private String mSmscode;
    private String mMessage;
    private boolean isOnPause = false;

    int i = 30;

    private static final int PAGE_3_ID = 0x3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_welcome_layout);

        // findViewById_(R.id.welcome_layout).setOnClickListener(this);

        mLogin = ReqFactory.buildInterface(this, Login.class);
        addCallback(mBaseCall);
        mPager = (ViewPager) findViewById(R.id.wel_pager);
        mPagerF0 = (RadioButton) findViewById(R.id.pager_0);
        mPagerF1 = (RadioButton) findViewById(R.id.pager_1);
        mPagerF2 = (RadioButton) findViewById(R.id.pager_2);

        mPager.setOnPageChangeListener(new OnPageChangeListener() {

            @Override
            public void onPageSelected(int arg0) {
                // TODO Auto-generated method stub
                switch (arg0) {
                    case 0:
                        mPagerF0.setChecked(true);
                        break;
                    case 1:
                        mPagerF1.setChecked(true);
                        break;
                    case 2:
                        mPagerF2.setChecked(true);
                        break;
                }
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {

            }

            @Override
            public void onPageScrollStateChanged(int arg0) {

            }
        });

        mViewList = new ArrayList<View>();
        @SuppressWarnings("static-access")
        LayoutInflater lf = getLayoutInflater().from(this);
        mPagerOne = lf.inflate(R.layout.welcome_pager_one, null);
        mPagerTwo = lf.inflate(R.layout.welcome_pager_one, null);
        mPagerThree = lf.inflate(R.layout.welcome_pager_three, null);
        mPagerThree.setId(PAGE_3_ID);
//        mPagerThree.setOnClickListener(this);
        ImageView mPagerImage = (ImageView) mPagerOne
                .findViewById(R.id.pager_image);
        mPagerImage.setBackgroundResource(R.drawable.app_user_guide_one);
        mPagerImage = (ImageView) mPagerTwo.findViewById(R.id.pager_image);
        mPagerImage.setBackgroundResource(R.drawable.app_user_guide_two);

        mViewList.add(mPagerOne);
        mViewList.add(mPagerTwo);
        mViewList.add(mPagerThree);
        mAdapter = new WelcomeAdapter(mViewList);
        mPager.setAdapter(mAdapter);
        initView();
        test();

        if (Build.VERSION.SDK_INT >= 23) {
            int readPhone = checkSelfPermission(Manifest.permission.READ_PHONE_STATE);
            int receiveSms = checkSelfPermission(Manifest.permission.RECEIVE_SMS);
            int readSms = checkSelfPermission(Manifest.permission.READ_SMS);
            int readContacts = checkSelfPermission(Manifest.permission.READ_CONTACTS);
            int readSdcard = checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE);

            int requestCode = 0;
            ArrayList<String> permissions = new ArrayList<String>();
            if (readPhone != PackageManager.PERMISSION_GRANTED) {
                requestCode |= 1 << 0;
                permissions.add(Manifest.permission.READ_PHONE_STATE);
            }
            if (receiveSms != PackageManager.PERMISSION_GRANTED) {
                requestCode |= 1 << 1;
                permissions.add(Manifest.permission.RECEIVE_SMS);
            }
            if (readSms != PackageManager.PERMISSION_GRANTED) {
                requestCode |= 1 << 2;
                permissions.add(Manifest.permission.READ_SMS);
            }
            if (readContacts != PackageManager.PERMISSION_GRANTED) {
                requestCode |= 1 << 3;
                permissions.add(Manifest.permission.READ_CONTACTS);
            }
            if (readSdcard != PackageManager.PERMISSION_GRANTED) {
                requestCode |= 1 << 4;
                permissions.add(Manifest.permission.READ_EXTERNAL_STORAGE);
            }
            if (requestCode > 0) {
                String[] permission = new String[permissions.size()];
                this.requestPermissions(permissions.toArray(permission), requestCode);
                return;
            }
        }
        registerSDK();
    }

    EventHandler eh = new EventHandler(){
        @Override
        public void afterEvent(int event, int result, Object data) {
            Message msg = new Message();
            msg.arg1 = event;
            msg.arg2 = result;
            msg.obj = data;
            handler.sendMessage(msg);
        }
    };

    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        registerSDK();
    }

    private void registerSDK() {
        // 启动短信验证sdk
        if ("moba6b6c6d6".equalsIgnoreCase(MobSDK.getAppkey())) {
            Toast.makeText(this, "注册码错误", Toast.LENGTH_SHORT).show();
        }
        //注册回调监听接口
        SMSSDK.registerEventHandler(eh);
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode != RESULT_OK) {
            return;
        }
    }

    private void test() {
        if (BuildConfig.DEBUG)
            mPagerF0.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    if (isChecked) {
                        mLoginBtn.setClickable(true);
                        mLoginBtn.getBackground().setAlpha(225);
                    } else {
                        mLoginBtn.setClickable(false);
                        mLoginBtn.getBackground().setAlpha(120);
                    }
                }
            });
    }

    private void initView() {
        mContext = this;
        mUserNameEdit = (EditText) mPagerThree.findViewById(R.id.et_phone);
        mLoginBtn = (Button) mPagerThree.findViewById(R.id.start_login);
        btn_get_smsCode = (Button) mPagerThree.findViewById(R.id.btn_get_smsCode);
        mSmscodeEdit = (EditText) mPagerThree.findViewById(R.id.et_smsCode);
        btn_get_smsCode.setOnClickListener(this);
        mLoginBtn.setOnClickListener(this);

        mLoginBtn.setClickable(false);
        mLoginBtn.getBackground().setAlpha(120);

        String currName = SharePreCacheHelper.getUserName(this);
        if (!TextUtils.isEmpty(currName)) {
            mUserNameEdit.setText(currName);
        }

        mSmscodeEdit.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before,
                                      int count) {
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                String userName = mUserNameEdit.getText().toString().trim();
                if (TextUtils.isEmpty(userName)) {
                    Toast.makeText(mContext, R.string.input_username,
                            Toast.LENGTH_SHORT).show();
                } else {
                    if (s.toString().length() < 4) {
                        mLoginBtn.setClickable(false);
                        mLoginBtn.getBackground().setAlpha(120);
                    } else {
                        mLoginBtn.setClickable(true);
                        mLoginBtn.getBackground().setAlpha(225);
                    }
                }
            }
        });
    }

    private void handleLogin() {
        mUserName = mUserNameEdit.getText().toString();
        mSmscode = mSmscodeEdit.getText().toString();

        if (TextUtils.isEmpty(mUserName) || TextUtils.isEmpty(mSmscode)) {
            Toast.makeText(this, "用户名和验证码不能为空！", Toast.LENGTH_SHORT).show();
        } else {
            Login.LoginReq mReq = new Login.LoginReq();
            mReq.setUsername(mUserName);
            mReq.setSmsCode(mSmscode);
            mLogin.loginAsync(mReq, mBaseCall);
            hiddenSoftInput();
            showWaitingDialog((ContextState) null);
        }

//        Intent intent = new Intent(WelcomeLogin.this, ActivityTabs.class);
//        intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
//        startActivity(intent);
//        finish();

//        String phoneNums = mSmscodeEdit.getText().toString();
//        SMSSDK.submitVerificationCode("86", phoneNums, mSmscodeEdit.getText().toString());
    }

    private BaseCall<Login.LoginResp> mBaseCall = new BaseCall<Login.LoginResp>() {
        @Override
        public void call(LoginResp resp) {
            statusCode = resp.getStatusCode();
            sStatus = resp.getStatus();
            mMsg = resp.getMessage();
            dimessWaitingDialog();
            //cancel for user register part
            if (resp.isRequestSuccess() && !isOnPause) {
                SharePreCacheHelper.setUserName(getApplicationContext(), mUserName);
                Intent intent = new Intent(WelcomeLogin.this, ActivityTabs.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
                startActivity(intent);
                finish();
            } else {
                mMessage = resp.getMessage();
                Slog.i(mMessage);
            }
        }
    };

    @RequiresApi(api = Build.VERSION_CODES.CUPCAKE)
    private void hiddenSoftInput() {
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(getWindow().getDecorView()
                    .getWindowToken(), 0);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onResume() {
        super.onResume();
        isOnPause = false;
        String currID = SharePreCacheHelper.getUserName(this);
        if (!TextUtils.isEmpty(currID)) {
            finish();
            return;
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        isOnPause = true;
        dimessWaitingDialog();
    }

    /**
     * handle mob sms code
     */
    private void handleSmscode() {
        String phoneNums = mUserNameEdit.getText().toString();
        // 1. 通过规则判断手机号
        if (!judgePhoneNums(phoneNums)) {
            return;
        } // 2. 通过sdk发送短信验证
        SMSSDK.getVerificationCode("86", phoneNums);

        // 3. 把按钮变成不可点击，并且显示倒计时（正在获取）
        btn_get_smsCode.setClickable(false);
        btn_get_smsCode.setText("重新发送(" + i + ")");
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (; i > 0; i--) {
                    handler.sendEmptyMessage(-9);
                    if (i <= 0) {
                        break;
                    }
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                handler.sendEmptyMessage(-8);
            }
        }).start();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.start_login:
                handleLogin();
                break;
            case R.id.btn_get_smsCode:
                handleSmscode();
                break;
            case PAGE_3_ID:
                hiddenSoftInput();
                break;
            default:
                break;
        }
    }

    /**
     * 判断手机号码是否合理
     *
     * @param phoneNums
     */
    private boolean judgePhoneNums(String phoneNums) {
        if (isMatchLength(phoneNums, 11)
                && isMobileNO(phoneNums)) {
            return true;
        }
        Toast.makeText(this, "手机号码输入有误！", Toast.LENGTH_SHORT).show();
        return false;
    }

    /**
     * 判断一个字符串的位数
     *
     * @param str
     * @param length
     * @return
     */
    public static boolean isMatchLength(String str, int length) {
        if (str.isEmpty()) {
            return false;
        } else {
            return str.length() == length ? true : false;
        }
    }

    /**
     * 验证手机格式
     */
    public static boolean isMobileNO(String mobileNums) {
        /*
         * 移动：134、135、136、137、138、139、150、151、157(TD)、158、159、187、188
         * 联通：130、131、132、152、155、156、185、186 电信：133、153、180、189、（1349卫通）
         * 总结起来就是第一位必定为1，第二位必定为3或5或8，其他位置的可以为0-9
         */
        String telRegex = "[1][358]\\d{9}";// "[1]"代表第1位为数字1，"[358]"代表第二位可以为3、5、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
        if (TextUtils.isEmpty(mobileNums))
            return false;
        else
            return mobileNums.matches(telRegex);
    }

    /**
     * progressbar
     */
    private void createProgressBar() {
        FrameLayout layout = (FrameLayout) findViewById(android.R.id.content);
        FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(
                WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT);
        layoutParams.gravity = Gravity.CENTER;
        ProgressBar mProBar = new ProgressBar(this);
        mProBar.setLayoutParams(layoutParams);
        mProBar.setVisibility(View.VISIBLE);
        layout.addView(mProBar);
    }

    /**
     *
     */
    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == -9) {
                btn_get_smsCode.setText("重新发送(" + i + ")");
            } else if (msg.what == -8) {
                btn_get_smsCode.setText("获取验证码");
                btn_get_smsCode.setClickable(true);
                i = 30;
            } else {
                int event = msg.arg1;
                int result = msg.arg2;
                Object data = msg.obj;
                Log.e("event", "event=" + event + " result: " + result + " data: " + data);
                if (result == SMSSDK.RESULT_COMPLETE) {
                    // 短信注册成功后，返回MainActivity,然后提示
                    if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {// 提交验证码成功
                        Toast.makeText(getApplicationContext(), "提交验证码成功",
                                Toast.LENGTH_SHORT).show();
                        Intent intent = new Intent(WelcomeLogin.this,
                                ActivityTabs.class);
                        startActivity(intent);
                    } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                        Toast.makeText(getApplicationContext(), "正在获取验证码",
                                Toast.LENGTH_SHORT).show();
                    } else {
                        ((Throwable) data).printStackTrace();
                    }
                }
            }
        }
    };

    @Override
    protected void onStop() {
        super.onStop();
        SMSSDK.unregisterEventHandler(eh);
    }
}
